from rest_framework.views import APIView
from apps.article import models, serializers, views
from rest_framework.response import Response
from rest_framework import status


# 按标签搜索文章
class SearchTagView(APIView):

    def get(self, request, tag):
        tag = models.Tag.objects.filter(name=tag).first()
        if not tag:
            return Response({'res': 'fail', 'msg': '标签不存在'}, status=status.HTTP_404_NOT_FOUND)
        articles = models.Article.objects.filter(tag=tag.id).order_by('-create_time')
        # 创建分页对象，获取分页数据
        pg = views.ArticlePagination()
        articles_pg = pg.paginate_queryset(articles, request, view=self)
        # 序列化出数据
        serializr = serializers.ArticleSerializer(instance=articles_pg, many=True)
        return pg.get_paginated_response(serializr.data)


# 按关键字搜索文章
class SearchKeywordView(APIView):

    def get(self, request, keyword):
        articles = models.Article.objects.filter(content__contains=keyword)
        # 创建分页对象，获取分页数据
        pg = views.ArticlePagination()
        articles_pg = pg.paginate_queryset(articles, request, view=self)
        # 序列化出数据
        serializr = serializers.ArticleSerializer(instance=articles_pg, many=True)
        return pg.get_paginated_response(serializr.data)
